package com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business

import android.app.Activity
import android.util.Log
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.bean.ConfigResultBean
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.MyHandler
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ADConfig
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement.LoadFacebookAd
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement.LoadGoogleAd
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement.LoadIronSourceAd
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.FaceBookInterstitialListener
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.GoogleInterstitialListener
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.IronSourceInterstitialListener
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.collections.ArrayList

// 要求同时缓存，高并发注意
class ADInterstitialManager private constructor() : GoogleInterstitialListener,
    FaceBookInterstitialListener, IronSourceInterstitialListener {
    //UnityInterstitialListener
    private var adQueue: PriorityQueue<ConfigResultBean.AdInfo>? = null // 存储AdInfo
    private val interstitialList =
        Collections.synchronizedList(ArrayList<ArrayList<ConfigResultBean.AdInfo>>())


    private var allGroupSize = 0           // 总共有几组 (目前3组)
    private var iCurrentInGroupSize = 0     // 当前这一组的大小 (2个)

    @Volatile
    private var iCurrentGroupIndex = AtomicInteger(0)  // 当前是第几组

    private var isShow = false

    @Volatile
    private var errorNum = AtomicInteger(0) //记录当前广告ID是否请求成功

    @Volatile
    private var successNum = AtomicInteger(0) //记录当前广告ID是否请求成功

    override fun onFacebookFailed(e: String) {
        errorNum.addAndGet(1)
        isRequestCurrentGroupNextID(iCurrentGroupIndex.get())
    }

    override fun onGoogleFailed(e: String) {
        errorNum.addAndGet(1)
        isRequestCurrentGroupNextID(iCurrentGroupIndex.get())
    }

    override fun onIronSourceFailed(e: String) {
        errorNum.addAndGet(1)
        isRequestCurrentGroupNextID(iCurrentGroupIndex.get())
    }

//    override fun onUnityFailed(error: String) {
//        errorNum.addAndGet(1)
//        isRequestCurrentGroupNextID(iCurrentGroupIndex.get())
//    }

    override fun onFacebookAdLoad(bean: ConfigResultBean.AdInfo) {
        successNum.set(1)
        createAndAdd(bean)
    }

    override fun onGoogleADLoad(bean: ConfigResultBean.AdInfo) {
        successNum.set(1)
        createAndAdd(bean)
    }

    @Synchronized
    override fun onIronSourceADLoad(bean: ConfigResultBean.AdInfo) {
        successNum.set(1)
        createAndAdd(bean)
    }

//    override fun onUnityADLoad(bean: ConfigResultBean.AdInfo) {
//        successNum.set(1)
//        createAndAdd(bean)
//    }

    @Synchronized
    fun createAndAdd(bean: ConfigResultBean.AdInfo) {
        if (adQueue == null) {
            adQueue = createQueue(iCurrentInGroupSize)
        }
        adQueue!!.offer(bean)
    }

    @Synchronized
    private fun isRequestCurrentGroupNextID(index: Int) {
        // 组内广告全部失败请求下一组
        if (interstitialList.size > 0) {
            if (errorNum.get() == interstitialList[if (index < interstitialList.size) iCurrentGroupIndex.get() else 0].size) {
                errorNum.set(0)
                requestNextGroup(index)
            }
        }
    }

    private fun requestNextGroup(index: Int) {
        val nextIndex = index + 1
        if (allGroupSize > 0) {
            if (nextIndex < allGroupSize) {
                iCurrentInGroupSize = interstitialList[nextIndex].size
                if (adQueue == null) adQueue = createQueue(iCurrentInGroupSize)
                interstitialGroupRequest(nextIndex)
            }
        }
    }

    companion object {
        val mInstance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            ADInterstitialManager()
        }
    }

    fun showInterstitialAD(activity: Activity?, placement: String): Boolean {
        val time:Int = ((System.currentTimeMillis() - AppSettingManager.readLong("interTime", 0)) / 1000).toInt()
        if (time in 1..199) {
            AppSettingManager.saveLong(System.currentTimeMillis(), "interTime")
        }
        // 判断是否是补位AD
        if (placement != "Supplement") {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_AD_SHOULD_DISPLAY, "type", placement)
        }

        if (adQueue == null) { // splash里还没加载完就展示了
            adQueue = createQueue(iCurrentInGroupSize)
            return false
        }

        if (interstitialList.size > 0) {
            if (adQueue!!.isEmpty() && iCurrentGroupIndex.get() >= interstitialList.size) {
                FlurryEventUtil.putDataToEvent(
                    EventType.TYPE_IS_READY,
                    "Interstitial",
                    "None_$time"
                )
                interstitialGroupRequest(0)
                return false
            } else {
                val adBean = adQueue!!.poll()  // 返回队首元素，队首元素出队列
                if (adBean != null) {
                    when (adBean.advertiser) {
                        ADConfig.ADMOB -> {
                            isShow = LoadGoogleAd.mInstance.showInterstitialAd(placement, time)
                        }
                        ADConfig.FB -> {
                            isShow = LoadFacebookAd.mInstance.showInterstitialAd(placement, time)
                        }
                        ADConfig.IS -> {
                            isShow =
                                LoadIronSourceAd.mInstance.showInterstitialAD(
                                    placement,
                                    adBean,
                                    time
                                )
                        }
//                        ADConfig.UNITY -> {
//                            isShow = LoadUnityAd.mInstance.showInterstitialAd(activity, placement)
//                        }
                    }
                } else {
                    FlurryEventUtil.putDataToEvent(
                        EventType.TYPE_IS_READY,
                        "Interstitial",
                        "None_$time"
                    )
                }
            }

            // 所有组别都失败下一次展示从头开始请求

            if (!isShow && adQueue!!.isEmpty() && iCurrentGroupIndex.get() >= interstitialList.size - 1) {
                interstitialGroupRequest(0)
            }


            //组内有任意一个请求成功从头开始请求
            if (adQueue!!.isEmpty() && successNum.get() > 0) {
                successNum.set(0)
                errorNum.set(0)
                interstitialGroupRequest(0)
            }
        } else {
            FlurryEventUtil.putDataToEvent(
                EventType.TYPE_IS_READY,
                "Interstitial",
                "None_$time"
            )
        }
        return isShow
    }


    fun initConfig(bean: ConfigResultBean.ConfigResultBeanData) {
        LoadGoogleAd.mInstance.setGoogleInterstitialListener(this)
        LoadFacebookAd.mInstance.setFaceBookInterstitialListener(this)
        LoadIronSourceAd.mInstance.setIronSourceInterstitialListener(this)
//        LoadUnityAd.mInstance.setUnityInterstitialListener(this)
        // 初始化数据
        interstitialList.clear()
        interstitialList.addAll(bean.ADID.Interstitial)
        allGroupSize = interstitialList.size

        iCurrentInGroupSize = if (interstitialList.isNotEmpty()) interstitialList[0].size else 0
        AppSettingManager.saveLong(System.currentTimeMillis(), "interTime")
        interstitialGroupRequest(0)
    }

    // 降序排列,创建Ad容器（取money最高的）
    private fun createQueue(size: Int): PriorityQueue<ConfigResultBean.AdInfo> {
        var reSize = 3
        if (size >= 1) {
            reSize = size
        }
        return PriorityQueue(reSize,
            Comparator<ConfigResultBean.AdInfo> { s1, s2 ->
                s2.cpminfo.toInt() - s1.cpminfo.toInt()
            })
    }

    /**
     * 要求同时请求多个广告商的Ad
     * 初始化会调用
     * 每一组都失败会调用下一组直至三组都失败停止
     */
    @Synchronized
    private fun interstitialGroupRequest(index: Int) {
        if (interstitialList.size > 0) {
            iCurrentGroupIndex.set(index)
            Log.e("IwsTestIndex", iCurrentGroupIndex.get().toString())
            MyHandler.instance?.let {
                it.post {
                    interstitialList[if (index < interstitialList.size) index else 0].forEach { data ->
                        when (data.advertiser) {
                            ADConfig.ADMOB -> {
                                LoadGoogleAd.mInstance.initInsertAD(data)
                            }
                            ADConfig.FB -> {
                                LoadFacebookAd.mInstance.initAndLoadInterstitial(data)
                            }
                            ADConfig.IS -> {
                                LoadIronSourceAd.mInstance.initInsertAD(data)
                            }
//                            ADConfig.UNITY -> {
//                                LoadUnityAd.mInstance.initInsertAD(data)
//                            }
                        }
                    }
                }
            }
        }
    }

//    @Synchronized
//    fun getInterstitialFirst() {
//        if (interstitialList.size > 0) {
//            interstitialList[0].forEach { data ->
//                when (data.advertiser) {
//                    ADConfig.ADMOB -> {
//                        LoadGoogleAd.mInstance.initInsertAD(data)
//                    }
//                    ADConfig.FB -> {
//                        LoadFacebookAd.mInstance.initAndLoadInterstitial(data)
//                    }
//                }
//            }
//        }
//    }

}